﻿using PagedList;
using RequirementAndBug.Common;
using RequirementAndBug.Common.Entities;
using RequirementAndBug.Common.Entities.RequireModels;
using RequirementAndBug.DAL.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RequirementAndBug.BLL
{
    public class BugService : BaseService
    {
        public IPagedList<RequireListItem> GetAllRequireList(Hashtable hs)
        {
            #region 旧查询
            //不加关联查询、不加分页版
            //List<RequireListItem> items = new List<RequireListItem>();
            //IQueryable<REQRequirement> list = LoadEntities<REQRequirement>(x => x.Status == 1);
            //if (list.Count() > 0)
            //{
            //    foreach (var r in list)
            //    {
            //        RequireListItem item = new RequireListItem();
            //        item.CreateTime = r.CreateTime;
            //        item.ProCategory = r.ProCategory;
            //        item.Title = r.Title;
            //        item.RequireID = Convert.ToInt32(r.RequireID);
            //        item.UserID = r.UserID;
            //        items.Add(item);
            //    }
            //}
            //return items;           

            //关联查询、不分页
            //var dataItems2=dataItems.Select(entity => new RequireListItem()
            //    {
            //        CreateTime = entity.req.CreateTime,
            //        ProCategory = entity.req.ProCategory,
            //        Title = entity.req.Title,
            //        RequireID = entity.req.RequireID,
            //        UserID = entity.req.UserID,
            //        NickName = entity.user.NickName,
            //        StatusStr= entity.req.Status==1?"正常":"禁用"
            //    }).ToList();
            //if (dataItems != null)
            //{
            //    items = dataItems2.OrderByDescending(x => x.CreateTime).ToList();
            //}
            //return items;
            #endregion


            List<RequireListItem> items = new List<RequireListItem>();
            var dataItems = Db.Set<REQRequirement>().Join(Db.Set<REQUser>(),
                req => req.UserID,
                user => user.UserID,
                (req, user) => new { req, user });

            if (hs.ContainsKey("Title"))
            {
                string title = hs["Title"].ToString();
                dataItems = dataItems.Where(entity => entity.req.Title.Contains(title));
            }

            if (hs.ContainsKey("StageStatus"))
            {
                int status = Convert.ToInt32(hs["StageStatus"]);
                dataItems = dataItems.Where(entity => entity.req.StageStatus == status);
            }

            if (hs.ContainsKey("Status"))
            {
                int status = Convert.ToInt32(hs["Status"]);
                dataItems = dataItems.Where(entity => entity.req.Status == status);
            }

            if (hs.ContainsKey("Procategory"))
            {
                int procategory = Convert.ToInt32(hs["Procategory"]);
                dataItems = dataItems.Where(entity => entity.req.ProCategory == procategory);
            }

            if (hs.ContainsKey("TargetUserID"))
            {
                int userID = Convert.ToInt32(hs["TargetUserID"]);
                dataItems = dataItems.Where(entity => entity.req.TargetUserID == userID);
            }           

            var dataItems2=dataItems.Select(entity => new RequireListItem()
                {
                    CreateTime = entity.req.CreateTime,
                    ProCategory = entity.req.ProCategory,
                    Title = entity.req.Title,
                    RequireID = entity.req.RequireID,
                    UserID = entity.req.UserID,
                    NickName = entity.user.NickName,
                    StatusStr= entity.req.Status==1?"正常":"禁用",
                    StageStatus=entity.req.StageStatus
                }).OrderByDescending(x => x.CreateTime);

            IPagedList<RequireListItem> pageList = dataItems2.ToPagedList<RequireListItem>(Convert.ToInt32(hs["PageIndex"]),Convert.ToInt32( hs["PageSize"]));
            return pageList;
        }

        /// <summary>
        /// 返回单个需求详情
        /// </summary>
        /// <param name="keyid"></param>
        /// <returns></returns>
        public RequireDetailItem GetRequireDetailInfo(int keyid)
        {
            RequireDetailItem item = new RequireDetailItem();
            IQueryable<REQRequirement> list = LoadEntities<REQRequirement>(x => x.RequireID == keyid);
            if (list.Count() > 0)
            {
                foreach (var r in list)
                {                    
                    item.CreateTime = r.CreateTime;
                    item.DeadlineTime = r.DeadlineTime;
                    item.ProCategory = r.ProCategory;
                    item.Title = r.Title;
                    item.RequireID = Convert.ToInt32(r.RequireID);
                    item.UserID = r.UserID;
                    item.TargetUserID = r.TargetUserID;
                    item.ProjectDesc = r.ProjectDesc;
                    break;
                }
            }
            return item;
        }
        /// <summary>
        /// 返回单个浏览需求详情
        /// </summary>
        /// <param name="keyid"></param>
        /// <returns></returns>
        public RequireScanDetailItem GetRequireScanDetailInfo(int keyid)
        {
            RequireScanDetailItem item = new RequireScanDetailItem();

            var detailObj = from r in Db.Set<REQRequirement>()
                            join createUser in Db.Set<REQUser>() on r.UserID equals createUser.UserID
                            join targetUser in Db.Set<REQUser>() on r.TargetUserID equals targetUser.UserID into targetUserView
                            from ddc in targetUserView.DefaultIfEmpty()
                            where r.RequireID == keyid
                            select new RequireScanDetailItem
                            {
                                CreateTime = r.CreateTime,
                                DeadlineTime = r.DeadlineTime,
                                ProCategory = r.ProCategory,
                                ProjectDesc = r.ProjectDesc,
                                RequireID = r.RequireID,
                                TargetUserName = ddc.NickName,
                                Title = r.Title,
                                UserName = createUser.NickName,
                                StageStatus = r.StageStatus,
                                Status = r.Status,
                                UserID=r.UserID,
                                FinishTime=r.FinishTime
                            };

            if (detailObj != null)
            {
                item = (RequireScanDetailItem)detailObj.FirstOrDefault();
            }

            return item;
        }

        public int AddBugInfo(RequireDetailItem item)
        {
            REQRequirement requirement = new REQRequirement();
            requirement.CreateTime = item.CreateTime;
            requirement.ProCategory = item.ProCategory;
            requirement.ProjectDesc = item.ProjectDesc;
            requirement.ProjectType = 1;
            requirement.Status = (int)EEntityStatus.Normal;
            requirement.StageStatus = (int)EBugStatus.Developing;
            requirement.TargetUserID = item.TargetUserID;
            requirement.Title = item.Title;
            requirement.UserID = item.UserID;
            requirement.DeadlineTime = item.DeadlineTime;
            
            requirement=SaveEntity(requirement);
            if (requirement != null)
                return 1;
            return 0;
        }

        public int DeleteBugInfo(RequireDeleteRequest request)
        {
            IQueryable<REQRequirement> list = LoadEntities<REQRequirement>(x => x.RequireID == request.RequireID);
            if (list.Count() > 0)
            {
                REQRequirement r = list.FirstOrDefault();
                r.Status = (int)EEntityStatus.Forbidden;
                
                r.UpdateTime = DateTime.Now;
                EditEntity(r);
                return 1;
            }   
            return 0;
        }

        public int EditBugInfo(RequireDetailItem item)
        {
            IQueryable<REQRequirement> list = LoadEntities<REQRequirement>(x => x.RequireID == item.RequireID);
            if (list.Count() > 0)
            {
                REQRequirement r = list.FirstOrDefault();                
                r.UpdateTime = DateTime.Now;

                r.ProCategory = item.ProCategory;
                r.ProjectDesc = item.ProjectDesc;
                r.TargetUserID = item.UserID;
                r.TargetUserID = item.TargetUserID;
                r.Title = item.Title;
                r.DeadlineTime = item.DeadlineTime;
                EditEntity(r);
                return 1;
            }                 
            return 0;
        }
        /// <summary>
        /// 改变需求状态
        /// </summary>
        /// <param name="targetStatus"></param>
        /// <param name="requireID"></param>
        /// <returns></returns>
        public int BugStageChange(EBugStatus targetStatus, int requireID)
        {
            IQueryable<REQRequirement> list = LoadEntities<REQRequirement>(x => x.RequireID == requireID);
            if (list.Count() > 0)
            {
                REQRequirement r = list.FirstOrDefault();

                r.StageStatus = (int)targetStatus;

                if (targetStatus == EBugStatus.Finish)
                {
                    r.FinishTime = DateTime.Now;
                    r.Status = (int)EEntityStatus.Forbidden;
                }
                //重新开发操作，清除完成时间
                if (targetStatus == EBugStatus.Developing)
                {
                    r.FinishTime = null;
                    r.Status = (int)EEntityStatus.Normal;
                }

                EditEntity(r);
                return RT.Success.Code;
            }
            return RT.NoSuccess.Code;        
        }
    }
}
